# -*- mode: org; fill-column: 100; -*-
#+TITLE: jq examples
#+AUTHOR: Zelphir Kaltstahl
#+DATE: [2023-05-07 So]
#+LANGUAGE: en
#+KEYWORDS: tool command-line JSON jq
#+EXCLUDE_TAGS: noexport, notexported
#+CREATOR: Emacs
#+STARTUP: overview
#+STARTUP: indent
#+STARTUP: align
#+STARTUP: shrink
#+STARTUP: inlineimages
#+STARTUP: entitiesplain
#+STARTUP: nologdone
#+STARTUP: nologreschedule
#+STARTUP: nologredeadline
#+STARTUP: nologrefile
#+PRIORITIES: A E E
#+TODO: TODO VALIDATE MAYBE WIP TESTING | DONE VALID CANCELED POSTPONED OBSOLETE
#+OPTIONS: ^:{}
#+OPTIONS: tags:nil
#+OPTIONS: tasks:t
#+OPTIONS: toc:2
#+OPTIONS: H:10
#+OPTIONS: p:nil
#+OPTIONS: pri:nil
#+OPTIONS: prop:nil
#+OPTIONS: todo:nil
#+OPTIONS: stat:nil
#+OPTIONS: |:t
#+OPTIONS: inline:nil

* Filter for objects containing specific keys

The following command selects only objects, which contain a key named ~"result"~.

#+begin_src sh
cat input.json | jq '. | select(.result != null)' > output.json
#+end_src

* Select only specific attributes/keys

The following command will keep only the ~"text"~ attribute of every object on the top layer of the input data.

#+begin_src sh
jq '. | {text}' input.json > output.json
#+end_src

* Construct objects from attributes selecting attributes conditionally

+ use ~attr1~ in the resulting object unconditionally
+ construct an attribute ~new_attr~
+ the ~new_attr~ attribute value will be an array
+ the array of ~new_attr~ will contains a selection of array elements of ~attr2~
+ the selection selects all elements, which have a ~some_key~, whose value is ~< 1~
+ use a file as input
+ redirect to an output file

#+begin_src sh
jq '. | {attr1, new_attr: [.attr2 | .[] | select(.some_key < 1)] }' input.json > output.json
#+end_src

Usage:

#+begin_src sh :results output verbatim drawer replace
{
cat <<EOF
{
  "result": [
    {
      "conf": 0.9,
      "end": 17.13,
      "start": 16.95,
      "word": "在"
    },
    {
      "conf": 1,
      "end": 17.73,
      "start": 17.13,
      "word": "这里"
    }
  ],
  "text": "在 这里"
}
EOF
} | jq '. | {text, result: [.result | .[] | select(.conf < 1)] }'
#+end_src

#+RESULTS:
:results:
{
  "text": "在 这里",
  "result": [
    {
      "conf": 0.9,
      "end": 17.13,
      "start": 16.95,
      "word": "在"
    }
  ]
}
:end:
